from django.shortcuts import render
from django.contrib import auth
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.viewsets import GenericViewSet
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from django.http import HttpResponseRedirect
import requests
from django.shortcuts import redirect
from utils.wx_helper import WxHelper
from django.conf import settings
from .serializers import UserSerializer, RoleSerializer, MenuSerializer, MenuTreeSerializer, MenuTreeForSelectSerializer, ConfigGroupSerializer, ConfigSerializer
from .models import User, Role, Menu, Config
from .filters import RoleFilter, UserFilter
from rest_framework.authtoken.models import Token
from .handles import get_wxloginurl, get_config_by_group, get_all_config_with_describe
# Create your views here.
def wxlogin(request):
    data = get_config_by_group(group='wxlogin')
    return render(request, 'system/wxlogin.html', data)

# def get_access_token(corpid='ww6b5a3ab7d26646d9', corpsecret='ohSoKEozbjG8fczG20VP6xnqWQdDOFPZxYrOWIW-fuw'):
#     url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}'.format(corpid=corpid, corpsecret=corpsecret)
#     data = requests.get(url).json()
#     return data.get('access_token')
#
# def get_userinfo(access_token, code):
#     url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={{ access_token }}&code={{ code }}'.format(access_token=access_token, code=code)
#     data = requests.get(url).json()
#     return data.get('UserId')
def main(request):

    if request.user.is_authenticated:
        return render(request, 'system/index.html')
    else:
        return redirect('/wxlogin')
    # code = request.GET.get('code')
    # if not code:
    #     return redirect('/wxlogin')
    # # access_token = get_access_token()
    # wxhelper = WxHelper(WX_CORP.get('corpid'), WX_CORP.get('agentid'), WX_CORP.get('corpsecret'))
    # UserId = wxhelper.get_userinfo(code)
    # user = User.objects.filter(username=UserId).first()
    # if user:
    #     auth.login(request, user)
    #     return render(request, 'system/index.html', {'UserId': UserId})
    # UserData = wxhelper.get_user(UserId)
    # serializer = UserSerializer(data=UserData)
    # if serializer.is_valid(raise_exception=True):
    #     serializer.save()
    return render(request, 'system/index.html')




class WxLoginViewSet(GenericViewSet):
    def list(self, request):
        code = request.GET.get('code')
        WX_CORP = get_config_by_group(group='wxlogin')
        wxhelper = WxHelper(WX_CORP.get('appid'), WX_CORP.get('agentid'), WX_CORP.get('secret'))
        UserId = wxhelper.get_userinfo(code)
        user = User.objects.filter(username=UserId).first()
        #
        # if user:
        #     auth.login(request, user)
        #     return Response({'code': 200, 'message': '登陆成功'})
        # serializer = UserSerializer(data={'username': UserId})
        if not user:
            UserData = wxhelper.get_user(UserId)
            serializer = UserSerializer(data=UserData)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                user = serializer.instance

        auth.login(request, user)
        token = Token.objects.filter(user=user).first()
        if not token:
            token = Token.objects.create(user=user)
        
        # return Response({'code': 200, 'message': '登陆成功'})
        # return render(request, 'system/index.html', {'UserId': UserId})
        # return redirect('/')
        # return redirect('/login?token={}'.format(token.key))
        response = HttpResponseRedirect('/')
        response.set_cookie('vue_admin_template_token', token.key)
        return response
    @action(methods=['GET'], detail=False)
    def info(self, *args, **kwargs):
        user = self.request.user
        if user.is_authenticated:
            token = Token.objects.get(user=user)
            return Response({'data':{'token': token.key,
                                     'name': user.name,
                                     'roles': ['admin' if user.is_superuser else 'user'],
                                     'avatar': 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'}})
        else:
            return Response(status=403)
    
    @action(methods=['GET'], detail=False)
    def uri(self, *args, **kwargs):
        wxloginurl = get_wxloginurl()
        return Response({'code': 20000, 'uri': wxloginurl})

class LogoutViewSet(GenericViewSet):
    def list(self, request):
        auth.logout(request)
        return Response({'code': 200, 'message': '注销成功'})





class RoleViewSet(viewsets.ModelViewSet):
    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    permission_classes = [IsAuthenticated]
    filter_class = RoleFilter

class MenuViewSet(viewsets.ModelViewSet):
    queryset = Menu.objects.all()
    serializer_class = MenuSerializer
    permission_classes = [IsAuthenticated]

class MenuTreeViewSet(viewsets.ViewSet):
    def list(self, request, *args, **kwargs):
        menu = Menu.objects.filter(parent=None)
        serializer = MenuTreeSerializer(menu, many=True)
        return Response({'code': 20000, 'data': serializer.data})

    @action(methods=['GET'], detail=False)
    def select(self, request, *args, **kwargs):
        menu = Menu.objects.filter(parent=None)
        serializer = MenuTreeForSelectSerializer(menu, many=True)
        return Response({'code': 20000, 'data': serializer.data})


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]
    filter_class = UserFilter


class ConfigViewSet(viewsets.ModelViewSet):
    queryset = Config.objects.all()
    serializer_class = ConfigSerializer
    permission_classes = [IsAuthenticated]
    
    

    @action(methods=['get'], detail=False)
    def groupitems(self, request):
        queryset = Config.objects.values('group').distinct()
        # queryset.group_by = 'group'

        serializer = ConfigGroupSerializer(queryset, many=True)
        return Response({'code': 20000, 'data': serializer.data})
    
    @action(methods=['get'], detail=False)
    def items(self, request):
        data = get_all_config_with_describe()
        return Response({'code': 20000, 'data': data})